package no.ntnu.fp.utils;

import java.sql.Date;
import java.sql.Time;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class TimeInterval {
	private final Date date;
	private final Time startTime, endTime;

	public TimeInterval(Date date, Time startTime, Time endTime) {
		this.date = date;
		this.startTime = startTime;
		this.endTime = endTime;
	}

	public TimeInterval(Element intervalElement) {
		this.date = Date.valueOf(XmlParser.getTextValue(intervalElement, "date"));
		this.startTime = Time.valueOf(XmlParser.getTextValue(intervalElement, "startTime"));
		this.endTime = Time.valueOf(XmlParser.getTextValue(intervalElement, "endTime"));
	}

	public Date getDate() {
		return date;
	}

	public Time getStartTime() {
		return startTime;
	}

	public Time getEndTime() {
		return endTime;
	}

	public boolean intersects(TimeInterval timeInterval) {
		
		//Date comparison is tricky - can we assume that the dates 
		//represent only their days, and disregards hour-of-day values?
		return date.toString().equals(timeInterval.getDate().toString())
		&& ((!endTime.after(timeInterval.getEndTime()) && endTime.after(timeInterval.getStartTime()))
		|| (!startTime.before(timeInterval.getStartTime()) && startTime.before(timeInterval.getEndTime())));
	}

	public Element toXml(Document doc) {
		Element intervalElement = doc.createElement("interval");
		intervalElement.appendChild(XmlParser.createElementWithValue(doc, "date", date.toString()));
		intervalElement.appendChild(XmlParser.createElementWithValue(doc, "startTime", startTime.toString()));
		intervalElement.appendChild(XmlParser.createElementWithValue(doc, "endTime", endTime.toString()));
		return intervalElement;
	}

	@Override
	public String toString() {
		return "Date " + this.date.toString() + ", starttime: " + 
		this.startTime.toString() + ", endtime " + endTime.toString();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((date == null) ? 0 : date.hashCode());
		result = prime * result + ((endTime == null) ? 0 : endTime.hashCode());
		result = prime * result
				+ ((startTime == null) ? 0 : startTime.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		TimeInterval other = (TimeInterval) obj;
		if (date == null) {
			if (other.date != null)
				return false;
		} else if (!date.equals(other.date))
			return false;
		if (endTime == null) {
			if (other.endTime != null)
				return false;
		} else if (!endTime.equals(other.endTime))
			return false;
		if (startTime == null) {
			if (other.startTime != null)
				return false;
		} else if (!startTime.equals(other.startTime))
			return false;
		return true;
	}		
}
